import React from 'react'
import {Button, Popconfirm, Icon, message, Modal, TreeSelect, Checkbox, Row, Col} from 'antd';
import { Link } from 'dva/router';
import { connect } from 'dva';
import {auditVideo, upDownVideo, moveToOther, getConfig, weixinMpList, weixinPush} from '../../../services/fetch';
import { changeStatus } from '../../../services/theme';

import { deepClone } from '../../../utils/request';
import ShowTitleListTheme from '../Add/ShowTitleListTheme'
import Authentication from "../../../components/authentication";
import ShowTitleListThemeCopy from "../Add/ShowTitleListThemeCopy";

@connect(({ video, theme }) => ({
    isShowModal: video.isShowModal,
    video,
    theme
}))
export default class VideoButton extends React.PureComponent {

    constructor(props) {
        super(props);

        this.state = {
            visible: this.props.visible,
            visible2: false,
            value: undefined,
            table_name: '',
            mplist: [],
            mp_checkbox:[],
            config_json:{}
        }
    }
    componentDidMount() {
        getConfig().then((res) => {
            if (res.data.code == 200) {
                // console.log(res);
                this.setState({
                    config_json: res.data.data.config_json
                })

            }
        })
    }


    showModal6 = () => {
        /**
         * 上下架视频
         */

        let wx_url = this.state.config_json.weixinUrl;
        if (wx_url && this.state.mplist.length == 0){
            weixinMpList(wx_url).then((res) => {

                if (res.data.code === 200) {
                    this.setState({
                        mplist:res.data.data
                    })
                }

            })
        }

        this.setState({
            visible6: true,
        });
    }
    // checkbox 改变
    checkboxChange=(checkedValues)=>{
        this.setState({
            mp_checkbox: checkedValues
        })
    }

    /**
     * 推送微信矩阵
     */
    handleOk6 = (e) => {
        if (this.state.mp_checkbox.length == 0){
            message.error('请选择推送的公众号');
            return;
        }
        this.setState({
            visible6: false,
        });
        let id = this.props.theme.selectedRowKeys
        let data = JSON.parse(JSON.stringify(this.props.theme.dataSource))

        let _this = this;
        let time = 0;
        let wx_url = this.state.config_json.weixinUrl;



        id.map((item, index) => {
            setTimeout(function () {
                let now_data = data.list[item];
                if (now_data['type'] != 1){
                    message.error('只能推送文章');
                }else{
                    let push_data = {
                        'attachments':now_data['information_img'],
                        'title':now_data['information_title'],
                        'summary':now_data['intro'],
                        'content':now_data['content'],
                        'reporter':now_data['create_user'],
                        'mpid':_this.state.mp_checkbox
                    }
                    let hideConfig = message.loading('推送中...', 0);
                    weixinPush(wx_url,push_data).then((res) => {
                        setTimeout(hideConfig, 100);
                        if (res.data.code === 200) {
                            message.success('推送成功');
                        }else{
                            message.error('推送失败');
                        }
                    })
                }


            }, time);
            time += 500;

        })

        this.setState({
            visible3: false,
        });;
    }
    handleCancel6 = () => {
        this.setState({
            visible6: false,
        });
    }
    showModal2 = () => {
        this.setState({
            visible2: true,
        });
    }
    /**
     * 移动到
     */
    handleOk = (e) => {
        this.setState({
            visible2: false,
        });
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].plate_information_id
        })
        if (this.state.value) {
            let data = {
                plate_information_ids: moreArr,
                theme_id: this.state.value
            }
            moveToOther(data).then((res) => {
                if (res.data.code === 200) {
                    this.props.dispatch({
                        type: 'theme/getTableList', payload: {
                            dataAugment: {
                                index: this.props.theme.index,
                                theme_id: this.props.theme.initTableName
                            }
                        }
                    })
                    this.props.dispatch({ type: 'theme/updateMoreDeal', data: [] });
                    message.success(res.data.msg)
                } else {
                    message.error(res.data.msg)
                }
            })
        }
    }

    handleCancel = (e) => {
        this.setState({
            visible2: false,
        });
    }
    /**
     * 批量 删除 视频列表数据
     */
    deleteAll = () => {
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        let isDelete = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].information_id
            isDelete[index] = dataSource.list[item].state
        })
        if (isDelete.indexOf(1) === -1) {
            let data = {
                information_ids: this.props.theme.selectedPlateIds,
                table_name: this.props.theme.initTableName
            }
            // for (let i = dataSource.list.length - 1; i >= 0; i--) {
            //     moreArr.map((item, ins) => {
            //         if (dataSource.list[i].information_id === item) {
            //             dataSource.list.splice(i, 1)
            //         }
            //     })
            // }
            // dataSource.total = dataSource.total - moreArr.length
            this.props.dispatch({
                type: 'theme/deleteTableList', payload: {
                    dataAugment: data
                }
            });
            this.props.dispatch({ type: 'updateMoreDeal', data: [] });
        } else {
            message.error('不可删除已上架物品')
        }
    }

    /**
     * 审核 状态处理 审核通过
     * 审核: 0:编辑状态 1:待审状态 2:终审通过 3:退回待编
     */
    //审核通过
    auditVideoFun = () => {
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].information_id
        })
        let data = {
            information_ids: moreArr,
            status: 2,
            table_name: this.props.theme.initTableName
        }
        this.auditVideoHandle(data, 2)
    }
    //审核拒绝
    auditVideoBack = () => {
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].information_id
        })
        let data = {
            information_ids: moreArr,
            status: 3,
            table_name: this.props.theme.initTableName
        }
        this.auditVideoHandle(data, 3)
    }
    //提交审核
    submitAduit = () => {
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].information_id
        })
        let data = {
            information_ids: moreArr,
            status: 1,
            table_name: this.props.theme.initTableName
        }
        this.auditVideoHandle(data, 1)
    }
    //审核处理请求封装
    auditVideoHandle = (data, num) => {
        changeStatus(data).then((res) => {
            if (res.data.code === 200) {
                let list = JSON.parse(JSON.stringify(this.props.theme.dataSource))
                list.list.map((item, index) => {
                    data.information_ids.map((i, ins) => {
                        if (item.information_id === i) {
                            item.status = num
                        }
                    })
                })
                this.props.dispatch({ type: 'theme/updateTableList', data: list });
                this.props.dispatch({ type: 'updateMoreDeal', data: [] });
                message.success(res.data.msg);
            } else {
                message.error(res.data.msg);
            }
        })
    }
    /**
   * 上架  下架
   * record 返回当前 数据
   */
    upVideo = () => {
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].information_id
        })
        let data = {
            information_ids: moreArr,
            state: 1,
            table_name: this.props.theme.initTableName
        }
        setTimeout(() => {

        }, 3000)
        this.upDownVideoFetch(data, 1)
    }
    upVideos = () => {
        let moreId = this.props.theme.selectedRowKeys
        let dataSource = JSON.parse(JSON.stringify(this.props.theme.dataSource))
        let moreArr = []
        moreId.map((item, index) => {
            moreArr[index] = dataSource.list[item].information_id
        })
        let data = {
            information_ids: moreArr,
            state: 0,
            table_name: this.props.theme.initTableName
        }
        setTimeout(() => {

        }, 3000)
        this.upDownVideoFetch(data, 0)
    }
    //封装 上下架 请求
    upDownVideoFetch = (data, num) => {
        upDownVideo(data).then((res) => {
            if (res.data.code === 200) {
                let list = JSON.parse(JSON.stringify(this.props.theme.dataSource))
                list.list.map((item, index) => {
                    data.information_ids.map((i, ins) => {
                        if (item.information_id === i) {
                            item.state = num
                        }
                    })
                })
                this.props.dispatch({ type: 'theme/updateTableList', data: list });
                this.props.dispatch({ type: 'updateMoreDeal', data: [] });
            }
            message.success(res.data.msg);
        })
    }
    showModal = () => {
        const { dispatch } = this.props;
        // window.PubSub.publish('addModal'); //发布订阅
        // dispatch({
        //     type:'theme/showModal'
        // })
        let url;
        if (window.location.origin.indexOf('localhost') > -1) {
            url = window.location.origin + window.location.search + '#/AddTheme/theme/' + this.props.themeId;
        } else {
            url = window.location.origin + '/application/fcinformation/web/' + window.location.search + '#/AddTheme/theme/' + this.props.themeId;
        }

        window.open(url);
        // dispatch({
        //     type: 'add/addView'
        // })
    }
    /**
     * 移动
     */
    moveSelect = (value, label, extra) => {
        let table_name = extra.triggerNode.props.table_name
        this.setState({
            key: value,
            value: extra.triggerNode.props.plate_id,
            table_name: table_name
        })
    }

    /**
     * 编辑
     */

    edit = () => {
        let list = this.props.theme.selectedPlateDatas;
        let flag = true;

        list.every(item => {
            if (item.status != 0 && item.status != 3) {
                flag = false;
                return false;
            }
        });
        if (flag) {
            let ids = this.props.theme.selectedPlateIds;
            ids = ids.join(',');
            let url;
            if (window.location.origin.indexOf('localhost') > -1) {
                url = window.location.origin + window.location.search + '#/Add/' + ids + '/edit';
            } else {
                url = window.location.origin + '/application/fcinformation/web/' + window.location.search + '#/Add/' + ids + '/edit';
            }

            window.open(url);
        } else {
            message.error('稿件状态只能是草稿或退回');
            return true;
        }
    }

    /**
     * 复制
     */
    copyModal = ()=>{
        this.setState({
            copyModalVisible:true
        })
    }
    render() {
        const { selectedRowKeys, treeList, quanxian } = this.props.theme;
        let addpushweixin;
        const { loginModal } = this.props.video;
        if (this.state.config_json.weixinPushSwitch && this.state.config_json.weixinUrl){
            //推送
            addpushweixin = () =>
                <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.showModal6}>
                    <Icon type="sound" />推送到微信
                </Button>
        }

        return (
            <div className='btn_group'>

                {/* <Button
                    type="defualt"
                    onClick={this.showModal}
                >
                    <Icon type="plus" theme="outlined" />新建资讯
                </Button> */}

                <ShowTitleListTheme id={this.props.theme.initTableName} />
                {/* <ShowTitleListThemeCopy id={this.props.theme.initTableName} /> */}

                <Popconfirm className="FooterPop" placement="topLeft" icon={null} title={"确认要删除所选资讯吗?"} onConfirm={this.deleteAll}  onCancel={() => { }} okText="确定" cancelText="取消"  >
                    <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} >
                        <Icon type="delete" theme="outlined" />
                        删除
                    </Button>
                </Popconfirm>

                {/*
                    <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.showModal2}>
                        <Icon type="scissor" theme="outlined" />移动
                </Button> */}

                {/* <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.edit}>
                    <Icon type="scissor" theme="outlined" />编辑
                </Button> */}
                <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.submitAduit}>
                    <Icon type="check" theme="outlined" />提交审核
                </Button>

                <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.auditVideoFun}>
                    <Icon type="check" theme="outlined" />审核通过
                </Button>

                <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.auditVideoBack}>
                    <Icon type="close" theme="outlined" />审核退回
                </Button>

                {/*
                    <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.upVideo}>
                        <Icon type="arrow-up" theme="outlined" />上架
                </Button>

                    <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.upVideos}>
                        <Icon type="arrow-down" theme="outlined" />下架
                </Button> */}

                {/*<Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.copyModal}>
                    <Icon type="arrow-down" theme="outlined" />复制
                </Button>*/}
                {/* <Button type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={this.auditVideoBack}>
                    <Icon type="close" theme="outlined" />审核退回
                </Button> */}
                {this.state.config_json.weixinPushSwitch && this.state.config_json.weixinUrl && Authentication(addpushweixin, 'push/addpush', loginModal)}

                <Modal
                    title="推送到"
                    visible={this.state.visible6}
                    onOk={this.handleOk6}
                    onCancel={this.handleCancel6}
                >

                    <Checkbox.Group onChange={this.checkboxChange} value={this.state.mp_checkbox}>
                        <Row>
                            {
                                this.state.mplist.map((item)=>{
                                    return(
                                        <Col key={item.id} style={{marginBottom:'15px'}} span={8}><Checkbox value={item.id}>{item.name}</Checkbox></Col>
                                    )
                                })
                            }
                        </Row>
                    </Checkbox.Group>
                </Modal>

                <Modal
                    title="移动到"
                    visible={this.state.visible2}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <TreeSelect
                        style={{ width: 300 }}
                        value={this.state.key}
                        dropdownStyle={{ maxHeight: 400}}
                        dropdownMatchSelectWidth
                        treeData={treeList}
                        placeholder="选择分类"
                        treeDefaultExpandAll
                        onChange={this.moveSelect}
                    />
                </Modal>
                <Modal
                    title="复制"
                    visible={this.state.copyModalVisible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                </Modal>
            </div>
        )
    }
}
